package com.future.light.hello.dt.chap04.stack_queue;

import java.util.Arrays;

public class StackX<T> {
	private int top = -1;
	private Object[] eleArray;
	
	public StackX(int MAX){
		eleArray = new Object[MAX];
	}
	
	public void cleanStack(){
		Arrays.fill(eleArray, null);
		top = -1;
	}
	
	public boolean isEmpty(){
		return top == -1;
	}
	
	@SuppressWarnings("unchecked")
	public T peek() throws Exception{
		if(top == -1)
			throw new Exception("空栈！");
		return (T) eleArray[top];
	}

	public void push(T ele) throws Exception{
		if(top == eleArray.length - 1)
			throw new Exception("栈已满，元素“"+ ele +"”不能插入！");
		top++;
		eleArray[top] = ele;
	}
	
	public void pop() throws Exception{
		if(top == -1)
			throw new Exception("空栈！");
		eleArray[top] = null;
		top--;
	}
	
	public int getLength(){
		return top+1;
	}
	
	public String toString(){
		String str = "";
		if(top > -1){
			int i = 0;
			while(i <= top){
				str += eleArray[i] + " ";
				i++;
			}
		}
		return str;
	}
	
	public static void main(String[] args) throws Exception {
		StackX<Integer> s = new StackX<Integer>(5);
		s.push(0);
//		s.push(1);
		s.push(2);
		s.push(3);
		s.push(4);
		s.push(5);
		System.out.println("length=" + s.getLength());
		System.out.println(s.toString());
		s.pop();
		s.pop();
		System.out.println(s.peek());
		System.out.println(s.toString());
	}

}
